package com.demo.k8s.controller;

import com.demo.k8s.feign.KubernestOutsideMiyaServiceFeign;
import com.demo.k8s.feign.KubernestProviderFeign;
import com.demo.k8s.feign.KubernestProviderIstioFeign;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.List;

@Slf4j
@RefreshScope
@RestController
public class KubernetsController {

    @Resource
    private DiscoveryClient discoveryClient;

    @Resource
    private KubernestProviderFeign kubernestProviderFeign;

    @Resource
    private KubernestProviderIstioFeign kubernestProviderIstioFeign;
    @Resource
    private KubernestOutsideMiyaServiceFeign kubernestOutsideMiyaServiceFeign;

    @GetMapping("/k8s/service")
    public List<String> getServiceList(){
        return discoveryClient.getServices();
    }

    @GetMapping("/k8s/instance")
    public List<ServiceInstance> getInstance(@RequestParam("name") String name){
        log.info("name = " + name);
        List<ServiceInstance> instances = discoveryClient.getInstances(name);
        log.info("instances = " + instances);
        return instances;
    }

    @GetMapping("/k8s/feign")
    public String feign(@RequestParam("name") String name) {
        log.info("请求参数：{}",name);
        String provider = kubernestProviderFeign.provider(name);
        log.info("provider = " + provider);
        return provider;
    }

    /**
     * 这个接口必须使用istio才能调用
     * @param name 请求参数
     * @return 返回结果信息
     * @throws UnknownHostException 异常
     */
    @GetMapping("/k8s/istio/feign")
    public String istioFeign(@RequestParam("name") String name) throws UnknownHostException {
        log.info("请求参数：{}, 本机ip:{}",name, InetAddress.getLocalHost());
        String provider = kubernestProviderIstioFeign.provider(name);
        log.info("provider = " + provider);
        return provider + "; service-k8s ip:" + InetAddress.getLocalHost();
    }

    @GetMapping("/url")
    public Date rewriteUrl() {
        Date date = new Date();
        log.info("date = {}", date);
        return date;
    }

    @GetMapping("/k8s/outside/service/hi")
    public String outSideService() {
        String respose = kubernestOutsideMiyaServiceFeign.hi();
        log.info("response:{}", respose);
        return respose;
    }
}
